package com.rtp2p.rtcoresdkdemo.main

import android.app.Application
import android.content.Context
import com.rtp2p.rtcoresdkdemo.base.BaseViewModel
import com.rtp2p.rtp2pcore.core.DeviceInfoRequest
import com.rtp2p.rtp2pcore.core.SearchApDevice
import com.rtp2p.rtp2pcore.utils.RTLogUtils

class MainViewModel(application: Application) : BaseViewModel(application) {
    val adapter = MainAdapter {
        queryDeviceInfo()
    }

    private var searchApDevice: SearchApDevice? = null

    fun init(context: Context) {
        searchApDevice = SearchApDevice(context) {
            if (it.success) {
                searchApDevice?.stopSearch()
                val deviceInfos = mutableListOf<MainAdapter.DeviceInfo>()
                deviceInfos.add(MainAdapter.DeviceInfo(it.data, "Ap Camera", true))
                adapter.onRefreshData(deviceInfos)
            } else {
                RTLogUtils.d("搜索 code= ${it.code} message = ${it.message}")
                queryDeviceInfo()
            }
        }
    }

    fun onStart() {
        searchApDevice?.startSearch()
    }

    fun onStop() {
        searchApDevice?.stopSearch()
    }

    private fun queryDeviceInfo() {
        DeviceInfoRequest.queryDeviceInfo {
            if (it.success) {
                val deviceInfos = mutableListOf<MainAdapter.DeviceInfo>()
                it.data.forEach {
                    deviceInfos.add(MainAdapter.DeviceInfo(it.deviceId, it.name, false))
                }
                adapter.onRefreshData(deviceInfos)
            }
        }
    }
}